package com.cmj.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmj.Utils.BeanCopyUtils;
import com.cmj.dao.CategoryMapper;
import com.cmj.domain.ResponseResult;
import com.cmj.domain.SystemConstants;
import com.cmj.domain.dto.CategoryDto;
import com.cmj.domain.entity.Category;
import com.cmj.domain.vo.CategoryExcelVo;
import com.cmj.domain.vo.CategoryVo;
import com.cmj.domain.vo.PageVo;
import com.cmj.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

import static com.cmj.domain.SystemConstants.ARTICLE_STATUS_NORMAL;
import static org.springframework.util.ObjectUtils.isEmpty;

/**
 * 分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2022-03-13 10:46:08
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    /***
     * 获取分类列表
     * @return 返回分类列表
     */
    @Override
    public ResponseResult getCategoryList() {
        //获取分类id
        Set<Long> CategoryId = categoryMapper.selCategoryId();
        //获取分类信息
        List<Category> categories = new ArrayList<>();
        for (Long aLong : CategoryId) {
            categories.add(categoryMapper.selCategoryList(aLong, ARTICLE_STATUS_NORMAL));
        }
        //分装到vo中
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        return ResponseResult.okResult(categoryVos);
    }

    @Override
    public ResponseResult<CategoryVo> getCategoryList(Integer pageNum, Integer pageSize, CategoryDto categoryDto) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //条件 字段名 值 boolean condition, R column, Object val
        wrapper.eq(StringUtils.hasText(categoryDto.getName()),Category::getName,categoryDto.getName());
        wrapper.eq(StringUtils.hasText(categoryDto.getStatus()),Category::getStatus,categoryDto.getStatus());

        Page<Category> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page,wrapper);
        PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult delCategory(Long[] id) {
        int i = categoryMapper.deleteBatchIds(Arrays.asList(id));
        if (i == 0){
            new RuntimeException(SystemConstants.DELETE_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<CategoryVo> addCategory(Category category) {
        int result = categoryMapper.insert(category);
        if (result == 0){
            new RuntimeException(SystemConstants.INSERT_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateCategory(Category category) {
        QueryWrapper<Category> linkQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Category> id = linkQueryWrapper.eq("id", category.getId());
        int result = categoryMapper.update(category, id);
        if (result == 0){
            new RuntimeException(SystemConstants.UPDATE_FAIL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<CategoryVo> getCategory(Long id) {
        Category category = categoryMapper.selectById(id);
        if (isEmpty(category)){
            new RuntimeException(SystemConstants.SELECT_FAIL);
        }
        CategoryVo categoryVo = BeanCopyUtils.copyBean(category, CategoryVo.class);
        return ResponseResult.okResult(categoryVo);
    }

    @Override
    public void exportCategory(HttpServletResponse response) throws IOException {
        List<Category> categories = categoryMapper.selectList(null);
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).autoCloseStream(Boolean.FALSE).sheet("分类表")
                    .doWrite(categoryVos);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @Override
    public ResponseResult<CategoryVo> getListAllCategory() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0);
        queryWrapper.eq("status",SystemConstants.STATUS_NORMAL);
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        if (isEmpty(categories)){
            new RuntimeException(SystemConstants.SELECT_FAIL);
        }
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        return ResponseResult.okResult(categoryVos);
    }
}
